# coding:utf-8

from flask import render_template, url_for, redirect, flash
from sqlalchemy import or_

from app.extensions import db
from app.forms import NotChoices
from app.op.constant import AreaType
from app.op.models import Area
from .models import WarZone
from .forms import WarZoneDetailForm
from . import war_zone_bp


@war_zone_bp.route('/war_zones')
def war_zones():
    """
    created by chenhj at 2017/12/15

    """
    data = WarZone.query.all()
    return render_template(
        'war_zones.html',
        data=data
    )


@war_zone_bp.route('/war_zone/add', methods=['GET', 'POST'])
def add_war_zone():
    """
    created by chenhj at 2017/12/15

    """
    form = WarZoneDetailForm()
    areas = Area.query.filter(
        Area.deleted_at == 0,
        Area.war_zone_id.is_(None),
        Area.type == AreaType.PROV.value
    )
    form.area_ids.choices = NotChoices + \
        [
            (str(area.id), area.name)
            for area in areas
        ]
    if form.validate_on_submit():
        zone = WarZone()
        form.populate_obj(zone)
        db.session.add(zone)
        db.session.flush()

        db.session.query(Area).filter(
            Area.id.in_(form.area_ids.data)
        ).update({
            'war_zone_id': zone.id
        }, synchronize_session='fetch')

        flash('新增成功')
        return redirect(url_for('war_zone_bp.war_zones'))
    return render_template('war_zone_add.html', form=form)


@war_zone_bp.route('/war_zone/edit/<zone_id>', methods=['GET', 'POST'])
def edit_war_zone(zone_id):
    """
    created by chenhj at 2017/12/15

    """
    data = WarZone.query.get_or_404(zone_id)
    area_ids = [str(x.id) for x in data.areas]
    form = WarZoneDetailForm(obj=data)
    areas = Area.query.filter(
        Area.deleted_at == 0,
        or_(
            Area.war_zone_id.is_(None),
            Area.war_zone_id == zone_id
        ),
        Area.type == AreaType.PROV.value
    )
    form.area_ids.choices = NotChoices + \
        [
            (str(area.id), area.name)
            for area in areas
        ]

    if form.validate_on_submit():
        form.populate_obj(data)
        db.session.query(Area).filter(
            Area.id.in_(area_ids)
        ).update({
            'war_zone_id': None
        }, synchronize_session='fetch')

        db.session.query(Area).filter(
            Area.id.in_(form.area_ids.data),
        ).update({
            'war_zone_id': zone_id
        }, synchronize_session='fetch')
        flash('修改成功')
        return redirect(url_for('war_zone_bp.war_zones'))

    form.area_ids.data = area_ids
    return render_template('war_zone_edit.html', form=form)
